<?php
/*
 * @Description: 企业微信类
 * @Author: QianLong
 * @Date: 2019-09-27 16:34:02
 * @LastEditors    : QianLong
 * @LastEditTime   : 2021-05-25 13:33:36
 */

namespace app\common\service;

use app\api\model\SysSetting;
use app\lib\exception\ApiException;
use Yurun\Util\HttpRequest;

class Wwork
{
    protected $setting;
    protected $redis;
    protected $http;
    public function __construct()
    {
        $this->setting = SysSetting::where('id', 1)->find();
        $this->redis = new QlRedis();
        $this->http = new HttpRequest;
    }
    public function getUserInfo($code)
    {
        $access_token = $this->getAccessToken();
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=' . $access_token . '&code=' . $code;
        $response = $this->http->get($url);
        $tokenar = json_decode($response->body(), true);
        if ($tokenar['errcode'] != 0) {
            throw new ApiException($tokenar['errmsg'] . ' [' . $tokenar['errcode'] . ']');
        }
        return $tokenar;
    }
    private function getAccessToken()
    {
        $time = time();
        $tokenurl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . $this->setting['ww_appid'] . '&corpsecret=' . $this->setting['ww_agent_secret'];
        if ($this->redis->hexists('qiyeweixin_token', $this->setting['ww_agentid']) > 0) {
            $data_s = $this->redis->hget('qiyeweixin_token', $this->setting['ww_agentid']);
            $token = unserialize($data_s);
            if (empty($token) || $token['extime'] < $time) {
                $response = $this->http->get($tokenurl);
                $tokenar = json_decode($response->body(), true);
                $token['token'] = $tokenar['access_token'];
                $token['extime'] = $tokenar['expires_in'] + $time;
                $this->redis->hmset('qiyeweixin_token', $this->setting['ww_agentid'], serialize($token));
            }
        } else {
            $response = $this->http->get($tokenurl);
            $tokenar = json_decode($response->body(), true);
            $token['token'] = $tokenar['access_token'];
            $token['extime'] = $tokenar['expires_in'] + $time;
            $this->redis->hmset('qiyeweixin_token', $this->setting['ww_agentid'], serialize($token));
        }
        return $token['token'];
    }
}
